<!-- 新增/编辑部门通知 -->
<template>
	<view class="mainPge">
		<!-- 公共头部 -->
		<headerPublic title="部门通知" @backfn="backfn" />
		<!--主体-->
		<view class="page-content outbottom">
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-lable">标题：</view>
					<uv-input v-model="pageInfo.title" placeholder="请输入文件标题" border="bottom"
						class="textleft"></uv-input>
				</view>
			</view>
			<view class="frct">
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						创建部门
						<text class="redico">*</text>
					</view>
					<uv-input border="none" v-model="pageInfo.deptName" readonly></uv-input>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						创建时间
						<text class="redico">*</text>
					</view>
					<view class="defaultstr" @click="$refs.datetimePicker.open()">{{ pageInfo.createTime }}</view>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						创建人
						<text class="redico">*</text>
					</view>
					<uv-input border="none" v-model="pageInfo.agentName" readonly></uv-input>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">联系电话</view>
					<uv-input border="none" v-model="pageInfo.telephone" readonly></uv-input>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						公告日期
						<text class="redico">*</text>
					</view>
					<view class="fr-row" @click="$refs.calendar.open()" style="width: 40%;">
						<view class="defaultstr" v-if="pageInfo.publishTime">{{ pageInfo.publishTime }}</view>
						<view class="qxzstr" v-else>请选择日期</view>
						<image src="/static/docmumentImg/ico-date.png" class="ico-date"></image>
					</view>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						发布范围
						<text class="redico">*</text>
					</view>
					<text class='defaultstr'>部门人员</text>
					<!-- <uv-input border="none" v-model="pageInfo.publishScopeName" readonly></uv-input> -->
				</view>
				<!-- <view class="fr-row frit">
					<view class="fr-lable fr-2">
						发布范围
						<text class="redico">*</text>
					</view>
					<uv-radio-group v-model="pageInfo.publishScopeName">
						<uv-radio size="15" activeColor="#2d75d7" :customStyle="{ margin: '8px' }"
							v-for="(item, index) in radiolist" :key="index" :label="item.name" :name="item.name"
							@change="publishScopechange"></uv-radio>
					</uv-radio-group>
				</view> -->
				<view class="fr-row frit" style="align-items: flex-start" v-if="pageInfo.publishScopeName == '指定传阅人'"
					@click="checkpersonTitel = '指定传阅人';getPerson('指定传阅人');">
					<view class="fr-lable fr-2">
						指定传阅人
						<text class="redico">*</text>
					</view>
					<view class="fr-colum frpp" style="max-width: 70%">
						<view class="go">
							<uv-icon name="arrow-right" color="#555" size="14"></uv-icon>
						</view>
						<text class="person">{{ pageInfo.readerNames }}</text>
					</view>
				</view>
				<view class="fr-row frit" style="border: none; padding-bottom: 0">
					<view class="fr-lable fr-2">是否回执</view>
					<uv-checkbox-group v-model="hzval" style="flex: inherit" @change="hzchange">
						<uv-checkbox size="15" activeColor="#2d75d7" shape="square" :customStyle="{ margin: '8px' }"
							v-for="(item, index) in radiolist1" :key="index" :label="item.name"
							:name="item.name"></uv-checkbox>
					</uv-checkbox-group>
				</view>
			</view>
			<view class="frct" v-for="(it, index) in auditItems" :key="index">
				<view class="fr-colum">
					<view class="fr-lable fr-2">审批意见：</view>
					<!-- 查看详情的时候-->
					<view>
						<view class="ct borderno">{{ it.memo }}</view>
						<view class="fr-row frit">
							<view class="fr-lable fr-2"></view>
							<view class="defaultstr" style="font-size: 26rpx">{{ it.operatorName }} {{ it.completeTime
								}}</view>
						</view>
					</view>
				</view>
			</view>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-lable">
						<text class="redico">*</text>
						正文：
					</view>
					<uv-textarea :maxlength="-1" autoHeight v-model="pageInfo.content" placeholder="请输入文件内容"
						style="margin-bottom: 10px"></uv-textarea>
				</view>
			</view>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-row fr-lable fr-2 fr-2-line">
						<text>附件</text>
						<DhUpload style="flex: none" upload-type="DEPART" :business-id="pageInfo.businessId"  @upload-success="handleFilesSuccess"  :selected-files="fileListFJ">
							<template #trigger="{ selectFile }">
							     <text class="c1">+添加</text>
							  </template>
						</DhUpload>
					</view>
					<view class="fiellist">
						<view class="fr-row flieit" v-for="(file, index) in fileListFJ" :key="index">
							<text class="tname">{{ file.fileName }}</text>
							<text class="tsize">{{ file.fileSize }}</text>
							<uv-icon name="close" color="#2D75D7" size="14" @click="deleteFile(index)"></uv-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-lable">
						<text class="redico">*</text>
						选择路径：
					</view>
					<uv-radio-group v-model="pageInfo.businessStatusName" class="bline">
						<uv-radio size="15" activeColor="#2d75d7" :customStyle="{ margin: '8px' }"
							v-for="(item, index) in radiolist3" :key="index" :label="item.name" :name="item.name"
							@change="businessStatuschange"></uv-radio>
					</uv-radio-group>
					<view class="choseP" v-if="pageInfo.businessStatus == 'UNDO'">
						<view class="itp" v-for="(item, index) in auditarry" :key="index">
							<image src="/static/docmumentImg/ico-defalutp.png" class="icopimg"></image>
							<text class="t1">{{ item }}</text>
							<image src="/static/docmumentImg/icdelt.png" class="icdelt"
								@click="deletPerson(index, item)"></image>
						</view>
						<view class="itp" @click="getPerson('选择审核人')">
							<image src="/static/docmumentImg/ico-addp.png" class="icopimg"></image>
							<text class="t2">添加审批人</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!--底部固定 -->
		<view class="bt-foot">
			<view class="bt bt1" @click="sumitFn('保存')"
				v-if="(tabtype == 'icreat' && (businessStatus == 'DRAFT' || businessStatus == 'REBACK')) || actionType == 'add'">
				保存
			</view>
			<view class="bt bt2" @click="sumitFn('提交')">提交</view>
		</view>
		<!-- 日历-->
		<uv-calendar ref="calendar" color="#2d75d7" iconColor="red" @confirm="dateconfirm"></uv-calendar>
	</view>
</template>

<script>
	import {
		getRequestUrl
	} from '@/utils/request.js'
	import {
		timeFormat
	} from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import {
		getauditInfo,
		getSaveDrafat,
		handelauditSubmit
	} from '@/api/partNotice.js';
	export default {
		name: 'noticeset',
		data() {
			return {
				checkpersonTitel: '添加审批人', //选人标题，
				actionType: 'add', //判断（seeinfo）是查看详情还是（add）新增还是（edit）编辑
				businessId: '', // 页面传过来的id只有查看和编辑的时候才使用业务id
				businessType: 'DEPART', //业务类型 all 是全委通知  这块可以默认为all了
				businessStatus: '',
				tabtype: 'notice', // 判断是那个tab的处理数据执行（notice是通知公告 icreat是我创建的 iagreen是我审批的）用来做一些字段显示隐藏
				pageInfo: {
					businessId: '', //autoMap
					businessType: '', //
					// 基本信息数据
					title: '', // 标题
					deptName: '', // 创建部门
					createTime: '', // 创建时间
					agentName: '', // 创建人
					telephone: '', //联系电话
					publishTime: '', //公告日期
					publishScopeName: '全部人员', // 发布范围选择
					publishScope: 'ALL', //发布范围:ALL(0, "全部人员"), DESIGNEE(1, "指定人员")
					readerNames: '', // 指定传阅人姓名（自定义展示数据）
					readerIds: '', // 指定传阅人id，逗号分开
					readerAccounts: '', // 指定传阅人的手机号（账号）
					receiptStatus: '', //是否需要回执0：不需要1：需要
					content: '', // 正文
					businessStatus: '', //选择路径
					businessStatusName: '', //选择路径名称
					auditorIds: '', // 添加审批人ids
					auditorNames: '', // 审批人名称
					auditorAccounts: '', // 添加审批人的手机号（账号）
					busiAttachIds: '' // 文件ids
				},
				hzval: [], //额外判断是否需要回执
				auditarry: [], // 页面用来显示的审批人数组
				fileListFJ: [], // 附件上传
				auditItems: [], // 审批意见
				radiolist: [{
						name: '全部人员',
						disabled: false
					}
				],
				radiolist1: [{
					name: '需要回执',
					disabled: false
				}],
				radiolist3: [{
						name: '送审',
						disabled: false
					},
					{
						name: '发布信息',
						disabled: false
					}
				]
			};
		},
		onLoad(res) {
			this.actionType = res.actionType ? res.actionType : 'add';
			this.businessId = res.businessId ? res.businessId : '';
			this.businessType = res.businessType ? res.businessType : 'DEPART';
			this.businessStatus = res.businessStatus ? res.businessStatus : '';
			this.tabtype = res.tabtype ? res.tabtype : 'notice';
			this.Init();
		},
		onShow() {
			this.circulateSumint();
		},
		methods: {
			Init() {
				this.getpageInfo();
			},
			// 删除审核人
			deletPerson(index) {
			  const fields = ['auditorIds', 'auditorNames', 'auditorAccounts'];
			  fields.forEach(key => {
			    this.pageInfo[key] = (this.pageInfo[key] || '').split(',').filter((_, i) => i !== index).join(',');
			  });
			  this.auditarry.splice(index, 1);
			},
			// 文件上传成功的返回
			handleFilesSuccess(files) {
			  if (!Array.isArray(files)) {
			    files = [files]; // 如果不是数组，转为数组
			  }
			  const newResponses = files
			    .filter(file => file?.response) // 过滤掉没有response的项
			    .map(file => file.response);   // 提取response
			  this.fileListFJ = [...this.fileListFJ, ...newResponses];
			  this.pageInfo.busiAttachIds = this.fileListFJ && this.fileListFJ.length > 0 ? this.fileListFJ.map((file) =>file.id).join() : null;
			  console.log('更新后的文件列表', this.fileListFJ);
			},
			// 删除文件
			deleteFile(index) {
				this.fileListFJ.splice(index, 1);
				this.pageInfo.busiAttachIds = this.fileListFJ && this.fileListFJ.length > 0 ? this.fileListFJ.map((file) =>file.id).join() : null;
			},
			// 去选择人
			getPerson(title) {
				uni.navigateTo({
					url: '/documentManagement/selectPerson/circulate?title=' + title + '&type=部门通知'+(title=='指定传阅人'?'&checkIds='+this.pageInfo.readerIds:'&checkIds='+this.pageInfo.auditorIds)
				});
			},
			// 获取基本信息数据
			getpageInfo() {
				getauditInfo({
					id: this.businessId,
					businessType: this.businessType
				}).then((res) => {
					// this.pageInfo = res.data;
					this.pageInfo = this.autoMap(res.data, this.pageInfo);
					this.auditItems = res.data.auditItems;
					this.fileListFJ = res.data.busiAttachs ? res.data.busiAttachs : [];
					this.pageInfo.busiAttachIds = res.data.busiAttachIds ? res.data.busiAttachIds : '';
					this.pageInfo.publishScope ='ALL'
					if (this.actionType == 'add') {
						this.pageInfo.businessStatus = '';
						this.pageInfo.businessStatusName = '';
						this.businessId = res.data.businessId;
						this.pageInfo.createTime = timeFormat(new Date().getTime(), 'yyyy-mm-dd');
						this.pageInfo.publishScopeName ='全部人员'
					}
					if (this.actionType == 'edit') {
						this.pageInfo.businessId = this.businessId;
						this.auditarry = res.data.auditorNames.split(',');
						(this.hzval = res.data.receiptStatus == 1 ? ['需要回执'] : []),
						(this.pageInfo.publishScopeName = res.data.publishScope == 'DESIGNEE' ? '指定传阅人' : '全部人员');
						if (res.data.businessStatus == 'DRAFT') {
							this.pageInfo.businessStatusName = '';
							this.pageInfo.businessStatus = '';
						}
					}
				});
			},
			// 选择传阅人和审核人
			circulateSumint() {
			  const chosedata = JSON.parse(uni.getStorageSync('selectPsersonData') || 'null') || null;
			  if (!chosedata) return;
			  if (this.checkpersonTitel === '指定传阅人') {
			    Object.assign(this.pageInfo, {
			      readerNames: chosedata.names,
			      readerIds: chosedata.ids,
			      readerAccounts: chosedata.mobiles
			    });
			    return;
			  }
			  if (this.checkpersonTitel === '添加审批人') {
			    // 合并新旧数据（自动去重）
			    const mergeData = (key) => {
			      const oldValues = (this.pageInfo[key]?.split(',') || []).filter(Boolean);
			      const newValues = (chosedata[key]?.split(',') || []).filter(Boolean);
			      return [...new Set([...oldValues, ...newValues])].join(',');
			    };
			    this.pageInfo.auditorIds = mergeData('ids');
			    this.pageInfo.auditorNames = mergeData('names');
			    this.pageInfo.auditorAccounts = mergeData('mobiles');
			    this.auditarry = this.pageInfo.auditorNames.split(',');
			  }
			  uni.setStorageSync('selectPsersonData', null);
			},
			// 保存草稿
			sumitFn(type) {
				if (type === '保存') {
					if (this.pageInfo.title == '' || this.pageInfo.content == '' ||
						!this.pageInfo.content) {
						uni.showToast({
							title: '请填写必填项！',
							icon: 'none',
							duration: 1500
						});
						return;
					}
					getSaveDrafat(this.pageInfo).then((res) => {
						this.showToastAndNavigate(res);
					});
				} else if (type === '提交') {
					//必填校验
					if (
						this.pageInfo.title == '' ||
						this.pageInfo.publishTime == '' ||
						this.pageInfo.publishScopeName == '' ||
						this.pageInfo.content == '' ||
						!this.pageInfo.content ||
						this.pageInfo.businessStatus == '' ||
						(this.pageInfo.businessStatus == 'UNDO' && this.pageInfo.auditorIds == '') ||
						(this.pageInfo.publishScopeName == '指定传阅人' && this.pageInfo.readerIds == '')
					) {
						uni.showToast({
							title: '请填写必填项！',
							icon: 'none',
							duration: 1500
						});
						return;
					}
					handelauditSubmit(this.pageInfo).then((res) => {
						this.showToastAndNavigate(res);
					});
				}
			},
			//提交保存成功公共处理
			showToastAndNavigate(res) {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 1500
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/documentManagement/departmentNotice/list?tabtype=2'
					});
				}, 1000);
			},
			// 是否回执
			hzchange(val) {
				console.log(val);
				this.pageInfo.receiptStatus = val.length > 0 ? 1 : 0;
			},
			//发布范围选择
			publishScopechange(val) {
				this.pageInfo.publishScopeName = val;
				this.pageInfo.publishScope = val == '全部人员' ? 'ALL' : 'DESIGNEE';
				this.pageInfo.readerIds = '';
				this.pageInfo.readerNames = '';
			},
			// 选择路径选择
			businessStatuschange(val) {
				this.pageInfo.businessStatusName = val;
				this.pageInfo.businessStatus = val == '送审' ? 'UNDO' : val == '发布信息' ? 'DONE' : '';
				this.checkpersonTitel = val == '送审' ? '添加审批人' : '';
				this.pageInfo.auditorIds = '';
				this.pageInfo.auditorNames = '';
				this.auditarry = [];
			},

			//日期选择
			dateconfirm(e) {
				this.pageInfo.publishTime = e[0];
			},
			autoMap(source, target) {
				const filteredSource = Object.keys(target).reduce((acc, key) => {
					if (source.hasOwnProperty(key)) {
						// 处理null值为''或[]
						const value = source[key];
						acc[key] = value === null ?
							(typeof target[key] === 'string' ? '' : []) :
							value;
					}
					return acc;
				}, {});

				return {
					...target,
					...filteredSource
				};
			},
			backfn() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	};
</script>
<style scoped lang="scss">
	@import '../../style/documentmanage.scss';

	::v-deep .uv-upload__wrap__preview {
		display: none;
	}
</style>